package com.mcp.mslocalmcp.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.sql.*;
import java.util.*;

@Service
public class MySqlService {
    
    private static final Logger logger = LoggerFactory.getLogger(MySqlService.class);
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Autowired
    private DataSource dataSource;
    
    /**
     * 执行SELECT查询
     */
    public List<Map<String, Object>> executeQuery(String sql, Object... params) {
        try {
            logger.info("执行查询SQL: {}", sql);
            if (params != null && params.length > 0) {
                return jdbcTemplate.queryForList(sql, params);
            } else {
                return jdbcTemplate.queryForList(sql);
            }
        } catch (Exception e) {
            logger.error("查询执行失败: {}", e.getMessage(), e);
            throw new RuntimeException("查询执行失败: " + e.getMessage());
        }
    }
    
    /**
     * 执行INSERT、UPDATE、DELETE操作
     */
    public int executeUpdate(String sql, Object... params) {
        try {
            logger.info("执行更新SQL: {}", sql);
            if (params != null && params.length > 0) {
                return jdbcTemplate.update(sql, params);
            } else {
                return jdbcTemplate.update(sql);
            }
        } catch (Exception e) {
            logger.error("更新操作执行失败: {}", e.getMessage(), e);
            throw new RuntimeException("更新操作执行失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取数据库中的所有表
     */
    public List<String> listTables() {
        try {
            String sql = "SHOW TABLES";
            List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);
            List<String> tables = new ArrayList<>();
            for (Map<String, Object> row : result) {
                tables.add(row.values().iterator().next().toString());
            }
            return tables;
        } catch (Exception e) {
            logger.error("获取表列表失败: {}", e.getMessage(), e);
            throw new RuntimeException("获取表列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取表结构
     */
    public List<Map<String, Object>> describeTable(String tableName) {
        try {
            String sql = "DESCRIBE " + tableName;
            return jdbcTemplate.queryForList(sql);
        } catch (Exception e) {
            logger.error("获取表结构失败: {}", e.getMessage(), e);
            throw new RuntimeException("获取表结构失败: " + e.getMessage());
        }
    }
    
    /**
     * 测试数据库连接
     */
    public boolean testConnection() {
        try {
            jdbcTemplate.queryForObject("SELECT 1", Integer.class);
            return true;
        } catch (Exception e) {
            logger.error("数据库连接测试失败: {}", e.getMessage(), e);
            return false;
        }
    }
    
    /**
     * 获取数据库信息
     */
    public Map<String, Object> getDatabaseInfo() {
        Map<String, Object> info = new HashMap<>();
        try {
            info.put("connected", testConnection());
            if (testConnection()) {
                info.put("tables", listTables());
                info.put("database", jdbcTemplate.queryForObject("SELECT DATABASE()", String.class));
                info.put("version", jdbcTemplate.queryForObject("SELECT VERSION()", String.class));
            }
        } catch (Exception e) {
            logger.error("获取数据库信息失败: {}", e.getMessage(), e);
            info.put("error", e.getMessage());
        }
        return info;
    }
} 